﻿using System;
using System.Collections;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using AccessControl.Business;
using AccessControl.Common;
using AccessControl.HardwareLibrary.FS80;
using AccessControl.Sida.FingerPrintCollector.FingerService;
using AccessControl.Sida.FingerPrintCollector.Login;
using AccessControl.Sida.FingerPrintCollector.Properties;
using AccessControl.Utility.BitmapUtility;
using AccessControl.Utility.Tools;
using DevExpress.XtraEditors;


namespace AccessControl.Sida.FingerPrintCollector.Form
{
    public partial class AddFingerPrintSimple : XtraForm
    {
        private bool hasScannerInstalled;

        #region Fields

        private readonly AccessControlDS.tblPersonRow _personRow;
        private FS80Device _fs80Device;
        private readonly BitmapCreator _bitmapCreator = new BitmapCreator();
        private readonly FingerCollectionBusiness _fingerCollectionBusiness = new FingerCollectionBusiness();
        private string _meessageParameter;
        private PictureBox _pictureBoxParameter;
        private byte[] _fingerParameter;
        private int _currentFingerIndex = -1;
        private ArrayList _pictureBoxArray;
        private readonly ArrayList _fingerPrintArray = new ArrayList(6);
        private Thread _thread;

        string errorFinger1;
        string errorFinger2;

        #endregion

        #region Constructor

        public AddFingerPrintSimple(AccessControlDS.tblPersonRow studentRow)
        {
            InitializeComponent();
            _personRow = studentRow;
        }

        #endregion

        #region Event

        private void AddFingerPrint_Load(object sender, EventArgs e){
            try
            {
                _fs80Device = new FS80Device();
                hasScannerInstalled = true;
            }
            catch (ApplicationException)
            {
                XtraMessageBox.Show("اسکنر اثر انگشت یافت نشد", "سیستم کنترل تردد آریابان",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                //Close();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("خطا\n" + ex.Message, "سیستم کنترل تردد آریابان",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                //Close();
            }

            textEditStudentCode.Text = _personRow.PersonRefNumber;
            textEditName.Text = _personRow.PersonFirstName;
            textEditFamily.Text = _personRow.PersonLastName;
            

            barButtonItemSubmit.Enabled = false;
            CreatePictrureBoxArray();

            if (hasScannerInstalled){
                _thread = new Thread(GetAllPictureBoxFingerPrint);

                _thread.Start();
            }else{
                _fingerPrintArray.Add(null);
                _fingerPrintArray.Add(null);
                _fingerPrintArray.Add(null);
                _fingerPrintArray.Add(null);
                _fingerPrintArray.Add(null);
                _fingerPrintArray.Add(null);
            }


        }

        private void AddFingerPrint_KeyDown(object sender, KeyEventArgs e)
        {

            if ((e.KeyCode == Keys.Enter)
                && (barButtonItemSubmit.Enabled))
                barButtonItemSubmit.PerformClick();

            if (e.KeyCode == Keys.Escape)
                Close();
        }

        private void barButtonItemSubmit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (SubmitFingerprint())
                Close();

            //var hasError = false;
            //if (!String.IsNullOrEmpty(errorFinger1))
            //{
            //    XtraMessageBox.Show(
            //        errorFinger1 == "3 Finger Not Equal"
            //            ? "اثر انگشت اول به درستی ثبت نشد، سه نمونه اثر انگشت دریافتی تطابق ندارند"
            //            : "خطا در سیستم، اثر انگشت اول به درستی ثبت نشد", "نرم افزار جمع آوری اثر انگشت  دانشجویان",
            //        MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //    hasError = true;
            //}
            //if (!String.IsNullOrEmpty(errorFinger2))
            //{
            //    XtraMessageBox.Show(
            //             errorFinger2 == "3 Finger Not Equal"
            //                 ? "اثر انگشت دوم به درستی ثبت نشد، سه نمونه اثر انگشت دریافتی تطابق ندارند"
            //                 : "خطا در سیستم، اثر انگشت دوم به درستی ثبت نشد", "نرم افزار جمع آوری اثر انگشت  دانشجویان",
            //             MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //    hasError = true;
            //}

            
            //if (!hasError)
            //    Close();
        }

        private bool SubmitFingerprint()
        {
            try
            {

                errorFinger1 = String.Empty;
                errorFinger2 = String.Empty;
                var newRow = new AccessControlDS.FingerCollectionDataTable().NewFingerCollectionRow();
                newRow.StudentCode = _personRow.PersonRefNumber;
                newRow.GroupUserID = LoginManager.CurrentUserID;
                newRow.Finger11 = (byte[])_fingerPrintArray[0];
                newRow.Finger12 = (byte[])_fingerPrintArray[1];
                newRow.Finger13 = (byte[])_fingerPrintArray[2];
                newRow.Finger21 = (byte[])_fingerPrintArray[3];
                newRow.Finger22 = (byte[])_fingerPrintArray[4];
                newRow.Finger23 = (byte[])_fingerPrintArray[5];
                _fingerCollectionBusiness.Insert(newRow);



                var fingerPrintEngineServerClient = new FingerPrintEngineServerClient("TcpBinding");
                fingerPrintEngineServerClient.ClientCredentials.Windows.ClientCredential.Domain = Settings.Default.Domain;
                fingerPrintEngineServerClient.ClientCredentials.Windows.ClientCredential.UserName = Settings.Default.Username;
                fingerPrintEngineServerClient.ClientCredentials.Windows.ClientCredential.Password = Settings.Default.Password;

                fingerPrintEngineServerClient.Open();
                fingerPrintEngineServerClient.EnrollFingerPrint(out errorFinger1, _personRow.pkPerson, 1, new[] { (byte[])_fingerPrintArray[0], (byte[])_fingerPrintArray[1], (byte[])_fingerPrintArray[2] });
                fingerPrintEngineServerClient.EnrollFingerPrint(out errorFinger2, _personRow.pkPerson, 2, new[] { (byte[])_fingerPrintArray[3], (byte[])_fingerPrintArray[4], (byte[])_fingerPrintArray[5] });
                fingerPrintEngineServerClient.Close();

                if (!String.IsNullOrEmpty(errorFinger1))
                    XtraMessageBox.Show(
                        errorFinger1 == "3 Finger Not Equal"
                            ? "اثر انگشت اول به درستی ثبت نشد، سه نمونه اثر انگشت دریافتی تطابق ندارند"
                            : "خطا در سیستم، اثر انگشت اول به درستی ثبت نشد", "نرم افزار جمع آوری اثر انگشت  دانشجویان",
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                if (!String.IsNullOrEmpty(errorFinger2))
                    XtraMessageBox.Show(
                             errorFinger2 == "3 Finger Not Equal"
                                 ? "اثر انگشت دوم به درستی ثبت نشد، سه نمونه اثر انگشت دریافتی تطابق ندارند"
                                 : "خطا در سیستم، اثر انگشت دوم به درستی ثبت نشد", "نرم افزار جمع آوری اثر انگشت  دانشجویان",
                             MessageBoxButtons.OK, MessageBoxIcon.Warning);

                return String.IsNullOrEmpty(errorFinger1) && String.IsNullOrEmpty(errorFinger2);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("خطا در سیستم، اطلاعات ثبت نشد\n" + ex.Message, "سیستم کنترل تردد آریابان",
                                      MessageBoxButtons.OK, MessageBoxIcon.Error);
                //WriteLog(errorFinger1, "SubmitFingerprint", eventLevelConstants.Warning);
                //WriteLog(errorFinger2, "SubmitFingerprint", eventLevelConstants.Warning);
                //WriteLog(ex.Message, "SubmitFingerprint", eventLevelConstants.Error);
                return false;
            }

        }


        private void AddFingerPrint_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_thread != null)
                _thread.Abort();
        }

        private void pictureBoxFinger11_Click(object sender, EventArgs e)
        {

            WaitForFinger(sender, 0);
        }

        private void pictureBoxFinger12_Click(object sender, EventArgs e)
        {

            WaitForFinger(sender, 1);
        }

        private void pictureBoxFinger13_Click(object sender, EventArgs e)
        {

            WaitForFinger(sender, 2);
        }

        private void pictureBoxFinger21_Click(object sender, EventArgs e)
        {
            WaitForFinger(sender, 3);
        }

        private void pictureBoxFinger22_Click(object sender, EventArgs e)
        {
            WaitForFinger(sender, 4);
        }

        private void pictureBoxFinger23_Click(object sender, EventArgs e){
            WaitForFinger(sender, 5);
        }

        private void WaitForFinger(object sender, int fingerIndex){
            if(ModifierKeys == (Keys.Control)){
                var fo = new OpenFileDialog();
                if(fo.ShowDialog(this)==DialogResult.OK){
                    var img = Image.FromFile(fo.FileName);
                    var bitmap = new Bitmap(img);
                    var bitArr = new byte[bitmap.Width * bitmap.Height];
                    for (var h = 0; h < bitmap.Height; h++)
                        for (var w = 0; w < bitmap.Width; w++)
                            bitArr[h * bitmap.Width + w] = bitmap.GetPixel(w, h).R;

                    _fingerParameter = bitArr;
                    _fingerPrintArray[fingerIndex] = bitArr;
                    _pictureBoxParameter = (PictureBox)sender;
                    _currentFingerIndex = fingerIndex;
                    _pictureBoxParameter.Image = img;
                    Thread.Sleep(500);
                    SetSubmitButtonEnabled(sender, EventArgs.Empty);
                }
            } else if (hasScannerInstalled){

                if ((_thread != null) && (_thread.IsAlive))
                    return;

                _pictureBoxParameter = (PictureBox) sender;
                _currentFingerIndex = fingerIndex;
                _thread = new Thread(GetSinglePictureBoxFingerPrint);
                _thread.Start();
            }
        }

        #endregion

        #region Privete Method

        private static void WriteLog(String message, String callerMethod, eventLevelConstants level)
        {
            LogFile.WriteLog(LogFile.DefaultLogfileLocation + "Fingerprint Collector\\" + DateTime.Now.Date.ToString("yyyyMMdd") + " " + "AddFingerPrintSimple " + callerMethod + ".txt", level, message);
        }

        private void CreatePictrureBoxArray()
        {
            _pictureBoxArray = new ArrayList(6)
			{
				pictureBoxFinger11,
				pictureBoxFinger12,
				pictureBoxFinger13,
				pictureBoxFinger21,
				pictureBoxFinger22,
				pictureBoxFinger23
			};
        }

        private byte[] GetSingleFingerPrint()
        {
            try
            {
                string result;
                byte[] frame;
                do
                {
                    result = _fs80Device.ReadFinger(out frame);
                    _meessageParameter = result;
                    Invoke(new EventHandler(SetMessage));
                } while (result != String.Empty);
                return frame;
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message, "GetSingleFingerPrint", eventLevelConstants.Error);
            }
            return null;
        }

        private void GetAllPictureBoxFingerPrint()
        {
            try
            {
                foreach (PictureBox pictureBox in _pictureBoxArray)
                {
                    _pictureBoxParameter = pictureBox;
                    Invoke(new EventHandler(SetPictureBoxBackgroundColor));
                    var finger = GetSingleFingerPrint();
                    _fingerPrintArray.Add(finger);

                    _fingerParameter = finger;
                    Invoke(new EventHandler(SetPictureBoxImage));
                    Thread.Sleep(1000);

                }
                Invoke(new EventHandler(SetSubmitButtonEnabled));
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message, "GetAllPictureBoxFingerPrint", eventLevelConstants.Error);
            }
        }

        private void GetSinglePictureBoxFingerPrint()
        {
            try
            {
                Invoke(new EventHandler(SetSubmitButtonDisabled));
                Invoke(new EventHandler(SetPictureBoxEmptyImage));
                var finger = GetSingleFingerPrint();
                _fingerPrintArray[_currentFingerIndex] = finger;

                _fingerParameter = finger;
                Invoke(new EventHandler(SetPictureBoxImage));
                Thread.Sleep(500);
                Invoke(new EventHandler(SetSubmitButtonEnabled));
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message, "GetSinglePictureBoxFingerPrint", eventLevelConstants.Error);
            }

        }

        private Bitmap CreatefingerPrintPicture(byte[] frame, Graphics graphics)
        {
            try
            {
                if (frame != null && frame.Length != 0)
                {
                    var size = _fs80Device.ImageSize;
                    var hBitmap = _bitmapCreator.CreateBitmap(graphics.GetHdc(), size, frame);
                    hBitmap.RotateFlip(RotateFlipType.Rotate180FlipX);
                    return hBitmap;
                }
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message, "CreatefingerPrintPicture", eventLevelConstants.Error);
            }
            return null;
        }

        private void SetMessage(object sender, EventArgs e)
        {
            labelMessage.Text = _meessageParameter;
        }


        private void SetPictureBoxBackgroundColor(object sender, EventArgs e)
        {
            _pictureBoxParameter.BackColor = Color.LightGreen;
        }

        private void SetPictureBoxImage(object Sender, EventArgs e)
        {
            _pictureBoxParameter.Image = CreatefingerPrintPicture(_fingerParameter, _pictureBoxParameter.CreateGraphics());
        }

        private void SetPictureBoxEmptyImage(object sender, EventArgs e)
        {
            if ((_pictureBoxParameter == pictureBoxFinger11) || (_pictureBoxParameter == pictureBoxFinger12) || (_pictureBoxParameter == pictureBoxFinger13))
                _pictureBoxParameter.Image = Resources.Hand1;
            if ((_pictureBoxParameter == pictureBoxFinger21) || (_pictureBoxParameter == pictureBoxFinger22) || (_pictureBoxParameter == pictureBoxFinger23))
                _pictureBoxParameter.Image = Resources.Hand02;
        }

        private void SetSubmitButtonEnabled(object sender, EventArgs e)
        {
            barButtonItemSubmit.Enabled = true;
        }

        private void SetSubmitButtonDisabled(object sender, EventArgs e)
        {
            barButtonItemSubmit.Enabled = false;
        }

        #endregion

        private void lblTest_DoubleClick(object sender, EventArgs e)
        {

        }

    }
}